<template>
	<view>
		<scroll-view style="height: 220rpx;padding-top: 22rpx;box-sizing: border-box;" class="scroll-row" scroll-x>
			<block v-for="(image,index) in imageLists" :key="index">
				<view
					style="width: 158rpx;height: 158rpx;border-radius: 10rpx;display: inline-block;margin-right: 20rpx;"
					class="position-relative">
					<image style="width: 158rpx;height: 158rpx;border-radius: 10rpx;" :src="image" :data-src="image"
						@tap="previewImage" mode=""></image>
					<image @tap="deleteImg(index)" src="/static/image/cha.png"
						style="width: 32rpx;height: 32rpx;top: 0;left: 0;" class="position-absolute">
					</image>
				</view>
			</block>
			<image v-if="imageList.length != mostUploadImage" @tap="chooseImage"
				style="width: 158rpx;height: 158rpx;margin-right: 20rpx;"
				src="https://image.hbei.vip/1629274393432_562.png" lazy-load></image>
		</scroll-view>
	</view>
</template>

<script>
	import permision from "@/common/permission.js"
	import request from "../utils/request.js"

	var sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	]
	var sizeType = [
		['compressed'],
		['original'],
		['compressed', 'original']
	]
	export default {
		props: {
			mostUploadImage: {
				type: Number,
				default: 3
			}
		},
		data() {
			return {
				title: 'choose/previewImage',
				imageList: [], //图片临时路径
				sourceTypeIndex: 2,
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeTypeIndex: 0,
				sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 3,
				count: [1, 2, 3, 4, 5, 6],
				num: false,
				imageLists: [], //图片网络路径
			}
		},
		onUnload() {
			this.imageList = [],
			this.sourceTypeIndex = 2,
			this.sourceType = ['拍照', '相册', '拍照或相册'],
			this.sizeTypeIndex = 2,
			this.sizeType = ['压缩', '原图', '压缩或原图'],
			this.countIndex = this.mostUploadImage;
		},
		methods: {
			//清空图片
			emptyImage() {
				this.imageList = []
				this.imageLists = []
			},
			//删除图片
			deleteImg(index) {
				this.imageList.splice(index, 1)
				this.imageLists.splice(index, 1)
			},
			sourceTypeChange: function(e) {
				this.sourceTypeIndex = parseInt(e.detail.value)
			},
			sizeTypeChange: function(e) {
				this.sizeTypeIndex = parseInt(e.detail.value)
			},
			countChange: function(e) {
				this.countIndex = e.detail.value;
			},
			chooseImage: async function() {
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif

				if (this.imageList.length === this.mostUploadImage) {
					let isContinue = await this.isFullImg();
					console.log("是否继续?", isContinue);
					if (!isContinue) {
						return;
					}
				}
				uni.chooseImage({
					sourceType: sourceType[this.sourceTypeIndex],
					sizeType: sizeType[this.sizeTypeIndex],
					count: this.mostUploadImage,
					success: (res) => {
						// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
						var tempFilePaths = res.tempFilePaths;
						//上传一张的时候
						if (res.tempFiles.length == 1) {
							if (res.tempFiles[0].size > 5242880) {
								uni.showToast({
									title: "大于5M图片无法上传",
									duration: 1000
								})
								tempFilePaths.splice(j, 1)
							}
						} else {
							//上传多张的时候
							for (var j = 0; j < res.tempFiles.length; j++) {
								if (res.tempFiles[j].size > 5242880) {
									this.num = true
									tempFilePaths.splice(j, 1)
								}
							}
						}

						if (tempFilePaths.length > this.mostUploadImage) {
							this.imageList.splice(this.mostUploadImage)
						}
						this.imageList = this.imageList.concat(tempFilePaths);
						if (this.imageList.length > this.mostUploadImage) {
							this.imageList.splice(this.mostUploadImage)
						}
						//支持多图上传
						for (var i = 0; i < tempFilePaths.length; i++) {
							wx.uploadFile({
								// http://192.168.31.139:8111/file/uploadFile
								//https://www.redifinetd.com/file/uploadFile
								//http://121.196.29.201:8103/file/uploadFile
								url: `${request.commonUrl}/file/uploadFile`,
								filePath: tempFilePaths[0],
								name: 'file',
								formData: {
									'type': 2
								},
								success: (res) => {
									let resData = JSON.parse(res.data)
									console.log(resData.code)
									if (resData.code === "S000") {
										this.imageLists.push(resData.data)
										if (this.imageLists.length > this.mostUploadImage) {
											this.imageLists.splice(this.mostUploadImage)
										}
										console.log('线上图片')
										console.log(this.imageLists)
										console.log("线上图片")
									}
								},
								fail: (res)=> {
								    console.log(res)
								}
							})
						}
					},
					fail: (err) => {
						console.log(err)
						// #ifdef APP-PLUS
						if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
							this.checkPermission(err.code);
						}
						// #endif
						// #ifdef MP
						uni.getSetting({
							success: (res) => {
								let authStatus = false;
								switch (this.sourceTypeIndex) {
									case 0:
										authStatus = res.authSetting['scope.camera'];
										break;
									case 1:
										authStatus = res.authSetting['scope.album'];
										break;
									case 2:
										authStatus = res.authSetting['scope.album'] && res
											.authSetting['scope.camera'];
										break;
									default:
										break;
								}
								if (!authStatus) {
									uni.showModal({
										title: '授权失败',
										content: '您未选择图片',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							}
						})
						// #endif
					}
				})
			},
			isFullImg: function() {
				return new Promise((res) => {
					uni.showModal({
						content: `已经有${this.mostUploadImage}张图片了,是否清空现有图片？`,
						success: (e) => {
							if (e.confirm) {
								this.imageList = [];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.imageList
				})
			},
			async checkPermission(code) {
				let type = code ? code - 1 : this.sourceTypeIndex;
				let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
					await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
						'android.permission.READ_EXTERNAL_STORAGE');

				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}

				return status;
			}
		}
	}
</script>

<style>
</style>
